/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>

*/
package cmd

import (
	"io"
	"os"
	"strings"

	"gitee.com/bjf-fhe/apicat/entry"
	"gitee.com/bjf-fhe/apicat/platform"
	"gitee.com/bjf-fhe/apicat/result"
	"gitee.com/bjf-fhe/apicat/source"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

// reportCmd represents the report command
var reportCmd = &cobra.Command{
	Use:   "report",
	Short: "生成访问日志报告",
	Long:  `读取Nginx或者阿里云导出的csv访问日志，分析访问行为，生成访问报告`,
	Run: func(cmd *cobra.Command, args []string) {

		api, baseUrl, err := rootConfig.LoadApi()
		if err == nil {

			if len(args) > 0 {

				rootConfig.file = args[0]

				var reader source.Reader
				reader, err = platform.GetSource(rootConfig.SourceMode, &rootConfig, false)
				if err != nil {
					cmd.PrintErr(err)
					os.Exit(1)
				}

				// if rootConfig.SourceMode == "csv" {
				// 	reader, err = csv.NewReader(logFile)
				// } else if rootConfig.SourceMode == "nginx" {
				// 	// Read from STDIN and use log_format to parse log records
				// 	reader, err = nginx.NewReader(logFile, nginxConfig, rootConfig.Format, rootConfig.TimeFormat)
				// } else if rootConfig.SourceMode == "aliyun" {
				// 	reader, err = aliyun.NewReader(args[0])
				// }

				if err != nil {
					cmd.PrintErr("读取日志文件出错", err)
					os.Exit(1)
				}

				var stat = result.NewStat()

				for recAndError := range reader.Records() {
					// rec, err := reader.Read()
					rec := recAndError.Entry
					err := recAndError.Error
					if err == io.EOF {
						logrus.Info("读取结束")
						break
					} else if err != nil {
						cmd.PrintErr("读取日志内容出错", err)
						os.Exit(1)
					}
					rec.SeperatePath()
					stat.Clients[rec.Client] = stat.Clients[rec.Client] + 1
					// Process the record... e.g.
					stat.Detail = append(stat.Detail, rec)
					var relatedPath = strings.TrimPrefix(rec.Url, baseUrl)

					if path, ok := api.Paths[relatedPath]; ok {
						method := path.GetOperation(rec.Method)
						if method != nil {
							rec.Legal = true
							rec.DetectErrorByDef(method)
							stat.Brief.LegalCount++
							continue
						} else {
							rec.ErrorType = entry.Illegal_Method
						}
					}
					stat.Brief.IllegalCount++
				}
				stat.ClientCount = len(stat.Clients)
				cmd.Println("分析完毕！")
				cmd.Printf("总共%d条日志信息，其中%d条为API定义url，%d条为API未定义Url请求", stat.Brief.Total(),
					stat.Brief.LegalCount, stat.Brief.IllegalCount)
				err = result.GenerateReport(stat)
				if err == nil {
					result.OpenResult()
				}
			} else {
				cmd.PrintErr("没有指定日志文件路径")
			}
		} else {
			cmd.PrintErrln(err)
			os.Exit(1)
		}
	},
}

func init() {
	rootCmd.AddCommand(reportCmd)

	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// reportCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// reportCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
